﻿using UnityEngine;

/// <summary>
/// 受伤
/// </summary>
public class FSMStateHurt : FSMStateBase
{
    protected override string getName => "hurt";

    public override bool isLoop { get; } = false;

    public override int priority { get; } = UnitDefine.STATE_PRIORITY_NON_INTERRUPTIBLE;

    private float stiffTime => UnitDefine.BASE_STIFF_TIME;    // TODO 添加属性修正
    private float speed => UnitDefine.KNOCK_BACK_SPEED;
    private float jumpHeight => UnitDefine.KNOCK_BACK_HEIGHT;

    protected override void OnEnter()
    {
        var axis = fsm.parameters.GetParam<float>("hurtAxis");
        if (axis == 0)
        {
            isEnd = true;
            return;
        }
        LookAt(axis);
        KnockedBack(axis);
    }

    protected override void OnExecute()
    {
        if (fsm.parameters.GetParam<bool>("isGround"))
            StopMove();
    }

    private void LookAt(float axis)
    {
        if (axis != 0)
            fsm.entity.animator.direction = new Vector3(-axis, 1, 1);
    }

    private async void KnockedBack(float axis)
    {
        var initialSpeedY = fsm.entity.physics.FFMEndSpeed(jumpHeight);
        var initialSpeedX = axis * speed;
        fsm.entity.physics.velocity = new Vector2(initialSpeedX, initialSpeedY);
        await Tools.Delay(stiffTime);
        fsm.parameters.SetParam("hurtAxis", 0f);
        isEnd = true;
    }

    private void StopMove()
    {
        var easingAxis = Mathf.MoveTowards(fsm.entity.physics.velocity.x / speed, 0, Time.deltaTime / UnitDefine.BASE_ACCE_TIME);
        fsm.entity.physics.velocity = new Vector2(easingAxis * speed, fsm.entity.physics.velocity.y);
    }
}